﻿using DAL.Interface;
using Microsoft.EntityFrameworkCore;
using Model;
using Model.DTO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DAL
{
    /// <summary>
    /// 基础DAL类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseDAL<T> : IBaseDAL<T> where T : Common, new()
    {
        private readonly MyDbContext db;
        /// <summary>
        /// 构造函数
        /// </summary>
        public BaseDAL(MyDbContext context)
        {
            this.db = context;
        }
        /// <summary>
        /// 数据上下文
        /// </summary>
        /// <returns></returns>
        public MyDbContext DbContext()
        {
            return this.db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Add(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Delete(T entity)
        {
            db.Remove(entity);
            return await db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Update(T entity)
        {
            db.Entry(entity).State = EntityState.Modified;
            return await db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 查询一个，通过id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> Find(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> List()
        {
            return await db.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 查询列表，少量的数据，默认5条
        /// </summary>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<List<T>> List(int limit = 5)
        {
            return await db.Set<T>().OrderByDescending(x => x.Id).Take(limit).ToListAsync();
        }
        /// <summary>
        /// 查询列表，通过id列表
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public  Task<List<T>> List(List<int> ids)
        {
            return  db.Set<T>().Where(x => ids.Contains(x.Id)).ToListAsync();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<List<T>> Pagination(Limit limit)
        {
            return await db.Set<T>().OrderByDescending(x => x.Id).Skip(limit.Skip).Take(limit.Count).ToListAsync(); ;
        }


    }
}
